package com.mdp.tpa.wechat.client.miniapp.login.ctrl;

import java.util.HashMap;
import java.util.Map;

import com.mdp.core.entity.Result;
import com.mdp.tpa.pub.client.SysClientService;
import com.mdp.tpa.pub.entity.SysUser;
import com.mdp.tpa.wechat.client.miniapp.login.service.WechatMiniAppLoginService;
import com.mdp.core.entity.Tips;
import com.mdp.safe.client.cache.TpaCodeRedisCacheService;
import com.mdp.tpa.wechat.client.miniapp.login.service.WechatMiniAppLoginHelpService;
import com.mdp.tpa.pub.entity.SysUserTpa;
import com.mdp.tpa.wechat.config.WxminiappProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
public class WechatMiniAppLoginController {

	@Autowired
	WechatMiniAppLoginService wechatMiniAppLoginService;

	@Autowired
	WechatMiniAppLoginHelpService wechatMiniAppLoginHelpService;

 	@Autowired
    WxminiappProperties properties;

	@Autowired
	SysClientService sysClientService;

	@Autowired
	TpaCodeRedisCacheService tpaCodeRedisCacheService;

	Logger log = LoggerFactory.getLogger(WechatMiniAppLoginController.class);

	/**
	 * 小程序授权登陆
	 * @param params
	 * @return
	 */
	@GetMapping(value = "/login/token",params = {"authType=wechat_mini_app"})
	Result wechatMiniAppLogin(@RequestParam Map<String,Object> params ){
		Map<String,Object> result=new HashMap<>();
		Tips tips = new Tips("微信登录成功");
		String code= (String) params.get("code");
		String autoRegister= (String) params.get("autoRegister");
		String forcePhoneno= (String) params.get("forcePhoneno");
		if(StringUtils.isEmpty(code)){
			return Result.error("code-required","code不能为空");
		}else{
			if(log.isDebugEnabled()) {
				log.debug("通过授权编号从redis缓存获取该授权应用的基本信息及微信appid等信息  AppTpAuth appid【"+properties.getAppid()+"】 ,appSecret【*************】");
				log.debug("向微信服务器获取用户基本信息，参数 appid【"+properties.getAppid()+"】,appSecret 长度【"+properties.getAppSecret().length()+"】,code【"+code+"】");
			}

			Map<String,Object> userInfo=wechatMiniAppLoginService.jscode2session(properties.getAppid(),properties.getAppSecret(),code);
			if(log.isDebugEnabled()) {
				log.debug("微信服务器返回的结果为"+userInfo);
			}
			String tpaOpenid=(String) userInfo.get("openid");
			String sessionKey=(String) userInfo.get("session_key");
			String unionid=(String) userInfo.get("unionid");

			SysUserTpa userTpaDb= sysClientService.getSysUserTpaByOpenid(tpaOpenid);

			String phoneno=(String)params.get("phoneno");

			tpaCodeRedisCacheService.put(code,code);
			tpaCodeRedisCacheService.put(tpaOpenid,sessionKey);

 			//如果数据库已注册，说明不是第一次登录，直接授权
			if(userTpaDb!=null){
				return wechatMiniAppLoginHelpService.loginByWechatMiniApp( userTpaDb.getOpenid(),code,null,userTpaDb.getPhoneno(),unionid);
 			}else{
				if(!"0".equals(forcePhoneno)){
					if(autoRegister!="0"){
   						userInfo.remove("session_key");
 						return Result.ok("tpa-auth-success-but-not-register-and-need-phoneno","授权成功").put("userInfo",userInfo).put("moreMsg","第三方授权成功，但是未注册到mdp平台,需要提交手机号码");
					}
				}
				if(autoRegister!="0"){
					// 第一次授权登录，进行自动注册入库
					SysUserTpa tpa=wechatMiniAppLoginHelpService.wechatUserInfoConvertToUserTpa(userInfo);
					wechatMiniAppLoginHelpService.autoRegisterByUserTpa(code,tpa,true);
					Result tokenMap=wechatMiniAppLoginHelpService.loginByWechatMiniApp( tpa.getOpenid(),code,null,tpa.getPhoneno(),unionid);
					tpaCodeRedisCacheService.remove(code);
					 return tokenMap;
				}else{
					// 手机号码返回前端，前端决定是否需要注册，再调用注册服务
   					userInfo.remove("session_key");
					return Result.ok("tpa-auth-success-but-not-register","授权成功").put("userInfo",userInfo).put("moreMsg","第三方授权成功，但是未注册到mdp平台");

				}
			}
		}
	}
	/**
	 * 小程序授权注册
	 * @param params
	 * @return
	 */
	@PostMapping(value = "/user/register/tpa",params = {"authType=wechat_mini_app"})
	@ResponseBody
	Result userRegister(@RequestBody Map<String,Object> params ){
 		String code= (String) params.get("code");
		String tpaOpenid=(String) params.get("openid");
		String unionid=(String) params.get("unionid");
		String redisCode=tpaCodeRedisCacheService.get(code);
		String sessionKey=tpaCodeRedisCacheService.get(tpaOpenid);

		if(StringUtils.isEmpty(redisCode)){
 			return Result.error("code-not-exists","code不存在，可能已过期");
		}else if(StringUtils.isEmpty(sessionKey)){
  			return Result.error("sessionKey-not-exists","essionKey不存在，可能已过期");
		}else{
			if(log.isDebugEnabled()) {
				log.debug("通过授权编号从redis缓存获取该授权应用的基本信息及微信appid等信息  appid【"+properties.getAppid()+"】 ,appSecret【*************】  ");
				log.debug("向微信服务器获取用户基本信息，参数 appid【"+properties.getAppid()+"】,appSecret 长度【"+properties.getAppSecret().length()+"】,code【"+code+"】");
			}


			SysUserTpa userTpaDb= sysClientService.getSysUserTpaByOpenid(tpaOpenid);
			if(userTpaDb!=null){
  				return Result.error("user-had-reg","该用户已注册，不能重复注册");
			}
 			//获取电话号码
			String phoneno=wechatMiniAppLoginHelpService.getPhonenoFromParams(params,sessionKey);
			SysUserTpa tpa=wechatMiniAppLoginHelpService.wechatUserInfoConvertToUserTpa(params);
			tpa.setPhoneno(phoneno);
			tpa.setAppid(properties.getAppid());

			SysUser user=wechatMiniAppLoginHelpService.autoRegisterByUserTpa(code,tpa,true);
			Result result=wechatMiniAppLoginHelpService.loginByWechatMiniApp( tpa.getOpenid(),code,user.getUserid(),tpa.getPhoneno(),unionid);
			tpaCodeRedisCacheService.remove(code);
			return result;
		}
	}
}
